package com.api.oa.controller;


import cn.hutool.core.date.DateField;
import cn.hutool.core.date.DateTime;
import cn.hutool.core.date.DateUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.jwt.JWTPayload;
import cn.hutool.jwt.JWTUtil;
import cn.hutool.jwt.signers.JWTSignerUtil;
import com.api.oa.config.EmServer;
import com.api.oa.model.entity.YQUser;
import com.api.oa.model.params.YQUserParams;
import com.api.oa.services.YQUserService;
import com.api.shopapi.controller.BaseController;
import com.api.shopapi.entity.MyResult;
import com.easemob.im.server.EMException;
import com.easemob.im.server.EMService;
import com.easemob.im.server.api.token.Token;
import com.easemob.im.server.model.EMUser;
import com.easemob.im.shaded.reactor.core.publisher.Mono;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.*;

import java.util.Date;
import java.util.HashMap;
import java.util.Map;

@RestController
@RequestMapping("/yq/yQUser")
public class YQUserController extends BaseController {

    @Autowired
    private YQUserService iYQUserService;

    @Value("${appKey}")
    private String appKey;



    @RequestMapping(value = "/add", method = RequestMethod.POST,name = "用户账号")
    public MyResult Add(@RequestBody YQUser entity) {
        try {
            return iYQUserService.add(entity) == 1 ? success(entity) : failed("操作失败");
        } catch (Exception e) {
            return anomalous(getExceptionMsg(e));
        }

    }

    @Autowired
    EmServer emServer;

    /**
     * 安卓登录
     *
     * @param entity
     * @return
     */
    @RequestMapping(value = "/mobile/login", method = RequestMethod.POST,name = "移动端登录")
    public MyResult login(@RequestBody YQUserParams entity) {
        try {

            YQUser login = iYQUserService.login(entity.getAccount(), entity.getPasswd());
            //注册环信
            if (StrUtil.isEmpty(login.getEmUuid())) {
                try {
                    String imUser = imService.createImUser("a" + String.valueOf(login.getUserId()), "123456", login.getUname());
                    login.setEmUuid(imUser);
                    iYQUserService.update(login);
                } catch (EMException e) {
                    e.printStackTrace(); //注册环信出问题
                }
            } else {
                emServer.updateImUser("a" + String.valueOf(login.getUserId()), login.getUname());
            }

            DateTime now = DateTime.now();
            DateTime newTime = now.offsetNew(DateField.YEAR, 100);
            Map<String, Object> payload = new HashMap<String, Object>();
            //签发时间
            payload.put(JWTPayload.ISSUED_AT, now);
            //过期时间
            payload.put(JWTPayload.EXPIRES_AT, newTime);
            //生效时间
            payload.put(JWTPayload.NOT_BEFORE, now);
            //载荷
            payload.put("userId", login.getUserId());
            payload.put("role", login.getUserType());
            payload.put("insCode", login.getBelongInsCode());
            String token = JWTUtil.createToken(payload, appKey.getBytes());
            Map<String, String> res = new HashMap<>();
            res.put("userId", login.getUserId() + "");
            res.put("userType", login.getUserType() + "");
            res.put("uname", login.getUname() + "");
            res.put("token", token);
            res.put("emUuid", login.getEmUuid());
            return success(res);
        } catch (Exception e) {
            return anomalous(e.getMessage());
        }

    }

    /**
     * 安卓登录
     *
     * @param entity
     * @return
     */
    @RequestMapping(value = "/mobile/passwd/reset", method = RequestMethod.POST,name = "移动端密码重置")
    public MyResult resetPassWd(@RequestBody YQUserParams entity) {
        try {
            return iYQUserService.resetPwd(entity.getUserId(), entity.getOrgPasswd(), entity.getPasswd()) == 1 ? success("修改成功") : failed("修改失败");
        } catch (Exception e) {
            return anomalous(e.getMessage());
        }

    }

    @Autowired
    EmServer imService;

    /**
     * 安卓登录
     *
     * @param entity
     * @return
     */
    @RequestMapping(value = "/pc/login", method = RequestMethod.POST,name = "PC端登录")
    public MyResult loginPc(@RequestBody YQUserParams entity) {
        try {

            YQUser login = iYQUserService.login(entity.getAccount(), entity.getPasswd());
            //注册环信
            if (StrUtil.isEmpty(login.getEmUuid())) {
                imService.createImUser("a" + String.valueOf(login.getUserId()), "123456", login.getUname());
            }
            DateTime now = DateTime.now();
            DateTime newTime = now.offsetNew(DateField.HOUR, 1);
            Map<String, Object> payload = new HashMap<String, Object>();
            //签发时间
            payload.put(JWTPayload.ISSUED_AT, now);
            //过期时间
            payload.put(JWTPayload.EXPIRES_AT, newTime);
            //生效时间
            payload.put(JWTPayload.NOT_BEFORE, now);
            //载荷
            payload.put("userId", login.getUserId());
            payload.put("role", login.getUserType());
            payload.put("insCode", login.getInsCode());
            String token = JWTUtil.createToken(payload, appKey.getBytes());
            Map<String, String> res = new HashMap<>();
            res.put("userId", login.getUserId() + "");
            res.put("emUuid", login.getEmUuid() + ""); //即时通讯
            res.put("token", token);
            return success(res);
        } catch (Exception e) {
            return anomalous(e.getMessage());
        }

    }

    /**
     * @return
     */
    @RequestMapping(value = "/pc/info", method = RequestMethod.GET,name = "用户信息")
    public MyResult info() {
        try {
            return success(iYQUserService.info());
        } catch (Exception e) {
            return anomalous(e.getMessage());
        }

    }


    @RequestMapping(value = "/pc/logout", method = RequestMethod.POST,name = "PC端登出")
    public MyResult logout() {
        try {


            return success(iYQUserService.info());
        } catch (Exception e) {
            return anomalous(e.getMessage());
        }

    }


    @RequestMapping(value = "/mobile/reg", method = RequestMethod.POST,name = "移动端注册")
    public MyResult register(@RequestBody YQUserParams entity) {
        try {
            return success(iYQUserService.register(entity.getAccount(), entity.getPasswd(), entity.getRole()));
        } catch (Exception e) {
            return anomalous(e.getMessage());
        }

    }


    @RequestMapping(value = "/remove/{id}", method = RequestMethod.POST,name = "删除账号")
    public MyResult remove(@PathVariable Long id) {
        try {
            iYQUserService.remove(id);
            return success("删除成功!");
        } catch (Exception e) {
            return anomalous(getExceptionMsg(e));
        }

    }


    @RequestMapping(value = "/update", method = RequestMethod.POST,name = "编辑账号")
    public MyResult update(@RequestBody YQUser entity) {
        try {
            return iYQUserService.update(entity) == 1 ? success("操作成功") : failed("操作失败");
        } catch (Exception e) {
            return anomalous(getExceptionMsg(e));
        }

    }


    @RequestMapping(value = "/list", method = RequestMethod.GET,name = "查询账号")
    public MyResult list(@RequestParam(defaultValue = "1") Integer pageIndex, @RequestParam(defaultValue = "20") Integer pageSize, @RequestParam(required = false) String insCode,
                         @RequestParam(required = false) String role, @RequestParam(defaultValue = "") String account) {
        try {
            return success(iYQUserService.list(insCode, role, account, pageIndex, pageSize));
        } catch (Exception e) {
            return anomalous(getExceptionMsg(e));
        }
    }


    @RequestMapping(value = "/ass/user", method = RequestMethod.GET,name = "查询评估人员账号")
    public MyResult AssUser(@RequestParam(required = false) String insCode,
                            @RequestParam(required = false) Integer role) {
        try {
            return success(iYQUserService.assUser(insCode, role));
        } catch (Exception e) {
            return anomalous(getExceptionMsg(e));
        }
    }

    @RequestMapping(value = "/one/{id}", method = RequestMethod.GET,name = "账号详情")
    public MyResult one(@PathVariable Long id) {
        try {
            return success(id == null ? null : iYQUserService.one(id));
        } catch (Exception e) {
            return anomalous(getExceptionMsg(e));
        }
    }

    @RequestMapping(value = "/contacts/{id}", method = RequestMethod.GET,name = "联系人账号")
    public MyResult contacts(@PathVariable Long id, @RequestParam(defaultValue = "1") Integer pageIndex, @RequestParam(defaultValue = "20") Integer pageSize, @RequestParam(required = false) String keyWord) {
        try {
            return success(id == null ? null : iYQUserService.contacts(id, keyWord, pageIndex, pageSize));
        } catch (Exception e) {
            return anomalous(getExceptionMsg(e));
        }
    }


    @RequestMapping(value = "/sync", method = RequestMethod.GET,name = "账号同步到环信")
    public MyResult sync() {
        try {
            return success(iYQUserService.sync());
        } catch (Exception e) {
            return anomalous(getExceptionMsg(e));
        }
    }


}
